// 切换主题
export function changeTheme(color: string = '#4466f0') {
	const root = document.documentElement
	root.style.setProperty('--el-color-primary', color)
	root.style.setProperty('--el-color-primary-light-3', mixColor(color, '#fff', 0.7))
	root.style.setProperty('--el-color-primary-light-5', mixColor(color, '#fff', 0.5))
	root.style.setProperty('--el-color-primary-light-7', mixColor(color, '#fff', 0.3))
	root.style.setProperty('--el-color-primary-light-8', mixColor(color, '#fff', 0.2))
	root.style.setProperty('--el-color-primary-light-9', mixColor(color, '#fff', 0.1))
	root.style.setProperty('--el-color-primary-dark-2', mixColor(color, '#000', 0.2))
}

function mixColor(color1: string, color2: string, weight: number): string {
	// 将颜色转换为RGB值
	const parseColor = (color: string) => {
		if (color.startsWith('#')) {
			color = color.slice(1)
			if (color.length === 3) {
				color = color
					.split('')
					.map((c) => c + c)
					.join('')
			}
			return [parseInt(color.slice(0, 2), 16), parseInt(color.slice(2, 4), 16), parseInt(color.slice(4, 6), 16)]
		}
		return [0, 0, 0]
	}

	const rgb1 = parseColor(color1)
	const rgb2 = parseColor(color2)

	// 计算混合后的RGB值
	const w = Math.max(0, Math.min(1, weight))
	const w2 = 1 - w
	const mixed = [
		Math.round(rgb1[0] * w + rgb2[0] * w2),
		Math.round(rgb1[1] * w + rgb2[1] * w2),
		Math.round(rgb1[2] * w + rgb2[2] * w2),
	]

	// 将RGB值转换为十六进制颜色
	const toHex = (n: number) => {
		const hex = n.toString(16)
		return hex.length === 1 ? '0' + hex : hex
	}

	return `#${toHex(mixed[0])}${toHex(mixed[1])}${toHex(mixed[2])}`
}
